package com.photoeditor.demo.ui.widget.image.compose;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.photoeditor.R;

/**
 * 展示颜色的圆形区域
 */
public class CircleColorView extends View {
    private RectF mRectF;
    private Paint mPaint;

    public CircleColorView(Context context) {
        super(context);
        init();
    }

    public CircleColorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        initAttr(attrs);
    }

    public CircleColorView(Context context, AttributeSet attrs,
                           int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        initAttr(attrs);
    }

    private void init() {
        setWillNotDraw(false);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Style.FILL);
        mRectF = new RectF();
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    private void initAttr(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getResources().obtainAttributes(attrs, R.styleable.CircleColorView);
            int color = typedArray.getColor(R.styleable.CircleColorView_showColor, Color.WHITE);
            mPaint.setColor(color);
            typedArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(mRectF.centerX(), mRectF.centerY(), mRectF.width() / 2, mPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mRectF != null) {
            mRectF.left = 0;
            mRectF.top = 0;
            mRectF.right = w;
            mRectF.bottom = h;
        }
    }

    public void setColor(int color) {
        mPaint.setColor(color);
        invalidate();
    }

    public int getColor() {
        return mPaint.getColor();
    }
}
